package net_thread_test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerThread extends Thread{

    @Override
    public void run(){
        try {
            //创建一个服务器对象
            ServerSocket serverSocket = new ServerSocket(8686);
            while(true){
                //使用accept方法进行客户端连接
                Socket socket = serverSocket.accept();
                //创建一个输入流来接收客户端的信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                while (true) {
                    String str = bufferedReader.readLine();
                    if (str != null && !str.equals("eof")) {
                        System.out.println("服务器接收：" + str);
                    } else {
                        break;
                    }
                }

                //创建一个输出流 向客户端传递信息
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
                bufferedWriter.write("已发送");
                bufferedWriter.newLine();
                bufferedWriter.flush();

                Scanner scanner = new Scanner(System.in);
                System.out.println("服务端发送：");
                String strMsg = scanner.nextLine();
                bufferedWriter.write(strMsg);
                bufferedWriter.newLine();
                // 自定义一个通信协议：消息发送末尾 使用 eof 作为结束标志位
                bufferedWriter.write("eof");
                bufferedWriter.write("\n");
                bufferedWriter.flush();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
